package com.chenwc.serialassistant.threadpool.supplier;

import com.chenwc.serialassistant.util.Common;
import gnu.io.SerialPort;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.function.Supplier;

/**
 * 发送文件
 *
 * @author chenwc
 */
public class SendFileSupplier implements Supplier<Integer> {

    private final static Logger logger = LoggerFactory.getLogger(SendFileSupplier.class);

    private final File file;
    private final SerialPort serialPort;
    private Integer sendLength;
    private final Label sendDataLength;

    public SendFileSupplier(File file, SerialPort serialPort, Integer sendLength, Label sendDataLength) {
        this.file = file;
        this.serialPort = serialPort;
        this.sendLength = sendLength;
        this.sendDataLength = sendDataLength;
    }

    @Override
    public Integer get() {
        if (file == null || !file.exists()) {
            Common.alert(Alert.AlertType.WARNING, "警告", "打开的文件为空或者不存在！");
            return null;
        }
        OutputStream os = null;
        try {
            byte[] bytes = FileUtils.readFileToByteArray(file);
            //获得串口的输出流
            os = serialPort.getOutputStream();
            Long t1 = System.currentTimeMillis();
            for (byte aByte : bytes) {
                os.write(new byte[]{aByte});
                //更新实际发送的数据长度
                sendLength = sendLength + 1;
                Platform.runLater(() -> {
                    //显示更新后的数据长度
                    sendDataLength.setText("Send: " + sendLength);
                });
            }
            Long t2 = System.currentTimeMillis();
            logger.info("发送文件耗时: {} ms", (t2 - t1));
        } catch (Exception e) {
            logger.error("Exception", e);
        } finally {
            try {
                if (os != null) {
                    os.flush();
                }
            } catch (IOException e) {
                logger.error("Exception", e);
            }
            IOUtils.closeQuietly(os);
        }
        return sendLength;
    }
}
